package com.yyang.xiqi.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import com.google.gson.Gson;
import com.yyang.xiqi.AppConstants;
import com.yyang.xiqi.utils.HttpUtils;
import com.yyang.xiqi.utils.StringUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HelperNotificationListenerService extends NotificationListenerService {
    private static final String TAG = "notification service";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Notification notification = sbn.getNotification();
        if (notification == null) {
            return;
        }
        Bundle extras = notification.extras;
        if (extras != null) {
            //包名
            String pkg = sbn.getPackageName();
            //通知标题
            String title = extras.getString(Notification.EXTRA_TITLE,"");
            //获取通知内容
            String content = extras.getString(Notification.EXTRA_TEXT,"");
            Log.d(TAG, String.format("收到通知，包名：%s，标题：%s，内容：%s", pkg, title, content));
            this.processOnReceive(pkg,title,content);
        }
    }

    private void processOnReceive(String pkg, String title, String content) {


        MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        if ("com.eg.android.AlipayGphone".equals(pkg)){
            // 支付宝
            if (checkMsgValid(title,content,"alipay")){
                Log.i(TAG, "checkMsgValid true");
                if (AppConstants.getNotifyUrl().equals("") || AppConstants.getKey().equals("")) {
                    return;
                }
//                if (!AppConstants.getNotify()) {
//                    return;
//                }
                HashMap<String,String> map = new HashMap<>();
                map.put("deviceid",AppConstants.getDeviceId());
                map.put("type","1");
                map.put("time",String.valueOf(System.currentTimeMillis()/1000));
                map.put("content",content);
                map.put("money",parseMoney(content));
                map.put("title","支付宝支付");
                String sign = getSign(map);
                Log.d(TAG, String.format("processOnReceive: %s",sign));
                map.put("sign",sign);
//                final JSONObject object = new JSONObject(data);
//                Log.d(TAG,  String.format("processOnReceive: %s",object.toString()));
                Gson gson = new Gson();
                String data = gson.toJson(map);
                final RequestBody requestBody;
                requestBody = RequestBody.create(JSON,data);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        HttpUtils.sendJsonPost(AppConstants.getNotifyUrl(),object.toString());

                        HttpUtils.getInstance().postJson(AppConstants.getNotifyUrl(), requestBody, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {

                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                            }
                        });
                    }
                }).start();
            }
        }
    }

    /**
     * 解析内容字符串，提取金额
     * @param content
     * @return
     */
    private static String parseMoney(String content){
        String pattern = "(\\d+\\.\\d{2})元";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);
        if (m.find()) {
            return m.group(1);
        }
        return "0.00";
    }


    /**
     * 检测消息是否正确 验证消息的合法性，防止非官方消息被处理
     * @param title
     * @param content
     * @param gateway
     * @return
     */
    private static boolean checkMsgValid(String title, String content, String gateway){
        if ("wxpay".equals(gateway)) {
            //微信支付的消息格式
            //1条：标题：微信支付，内容：微信支付收款0.01元(朋友到店)
            //多条：标题：微信支付，内容：[4条]微信支付: 微信支付收款1.01元(朋友到店)
            Pattern pattern = Pattern.compile("^((\\[\\+?\\d+条])?微信支付:|微信支付收款)");
            Matcher matcher = pattern.matcher(content);
            return "微信支付".equals(title) && matcher.find();
        }else if ("alipay".equals(gateway)){
            //支付宝的消息格式，标题：支付宝通知，内容：支付宝成功收款1.00元
            return "收款通知".equals(title) || "收钱码到账通知".equals(title);
        }
        return false;
    }


    public void cancelNotification(StatusBarNotification sbn) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cancelNotification(sbn.getKey());
        } else {
            cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
        }
    }

    private String getSign(HashMap<String,String> data) {
        String sb = "";
        String[] key = new String[data.size()];
        int index = 0;
        for (String k : data.keySet()) {
            key[index] = k;
            index++;
        }
        Arrays.sort(key);
        for (String s : key) {
            sb += s + "=" + data.get(s) + "&";
        }
        sb = sb.substring(0, sb.length() - 1);
        // 将得到的字符串进行处理得到目标格式的字符串
        sb += "&&key=" + AppConstants.getKey();
//        Log.d(TAG, String.format("getSign: %s",sb));
//        try {
//            sb = URLEncoder.encode(sb, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }// 使用常见的UTF-8编码
//        sb = sb.replace("%3D", "=").replace("%26", "&");
        return StringUtils.md5(sb);
    }
}
